import { useState, useEffect } from 'react';
import { Form, Select, Button } from 'antd';
import { axconst } from '@/shared/axconst';
import { AxValidator } from '../AxValidator';
import AxSelectForm from '../../AxSelectForm';

const FormItem = Form.Item;
const { Option } = Select;
const {
  inlineFormItemLayout,
  inlineFormItemLayoutAllRowTwo,
  inlineFormItemLayoutAllRowThree,
} = axconst;
/**
 * 自定义下拉框
 * @param label 标签
 * @param field 字段名称
 * @param value 值
 * @param placeholder 占位符
 * @param required 是否必填
 * @param searchFormProps 查询表单的属性
 * @param message 提示信息（如果添加了，所有错误提示为改信息）
 * @param validator 自定义验证函数
 * @param hidden 是否隐藏
 */
export function AxSelectWithForm(props) {
  const [value, setValue] = useState([]);
  const [data, setData] = useState([]);
  const [searchFormVisible, setSearchFormVisible] = useState(false);
  const { axvalue = [], formItemLayoutFromProps = null, searchFormProps: searchFormPropsFromProps = {}, ...rest } = props;
  /** 名称字段 */
  const displayField = searchFormPropsFromProps.displayField || 'name';
  /** 值字段 */
  const valueField = searchFormPropsFromProps.validator || 'id';
  let formItemLayout = {};
  switch (props.wholerow) {
    case 'two':
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case 'three':
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }
  useEffect(() => {
    setValue(axvalue);
  }, []);
  /** 因为是箭头函数，所以要写在searchFormProps之前 */
  const handleCreate = (d) => {
    setData(d);
    setValue(d.map(i => i[valueField]));
    setSearchFormVisible();
    return Promise.resolve();
  }
  let searchFormProps = {
    title: props.label,
    visible: searchFormVisible,
    handleVisible: setSearchFormVisible,
    handleCreate: handleCreate,
    selectedData: data,
    ...searchFormPropsFromProps,
  };
  const handleChange = val => {
    const { onChange } = props;
    setValue(val);
    setData(data.filter(i => val.findIndex(j => i[valueField] === j) > -1))
    if (onChange) {
      onChange(val);
    }
  }
  return props.hidden ? null : (
    <FormItem {...formItemLayout} label={props.label}>
      {props.form.getFieldDecorator(props.field, {
        initialValue: value,
        rules: [
          {
            label: props.label,
            required: props.required,
            message: props.message,
            validator: props.validator ? props.validator : AxValidator,
          },
        ],
      })(
        <>
          <Select
            mode='multiple'
            style={{ width: '95%' }}
            allowClear={true}
            placeholder={props.placeholder ? props.placeholder : `请选择${props.label}`}
            value={value}
            onChange={handleChange}
            {...rest}
          >
            {data &&
              data.map((d, idx) => (
                <Option
                  key={idx}
                  value={d[valueField] === true ? true : d[valueField] === false ? false : d[valueField]}
                >
                  {d[displayField]}
                </Option>
              ))}
          </Select>
          <Button
            type='link'
            icon='search'
            style={{ width: '5%' }}
            onClick={() => setSearchFormVisible(true)}
          />
          {searchFormVisible && <AxSelectForm {...searchFormProps} />}
        </> ,
      )
      }
    </FormItem >
  );
}
